package algorithm.leetcode;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * 说明:
 * <p>
 * 所有输入只包含小写字母 a-z 。
 *
 * @author: zhouj-j
 * @since: 2018/7/6
 */
public class __014_longest_common_prefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        char[][] chars = new char[strs.length][];
        int minLen = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            chars[i] = strs[i].toCharArray();
            if (chars[i].length < minLen) {
                minLen = chars[i].length;
            }
        }
        int i = 0;
        loop:
        for (; i < minLen; i++) {
            char c = chars[0][i];
            for (int j = 1; j < chars.length; j++) {
                if (c != chars[j][i]) {
                    break loop;
                }
            }
        }
        return new String(chars[0], 0, i);
    }

    public static void main(String[] args) {
        System.out.println(new __014_longest_common_prefix().longestCommonPrefix(new String[]{"123", "13", "1"}));
    }
}
